/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.security.config;

import io.iec.edp.caf.commons.utils.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangyandong
 */
public class WebSecurityFilter implements Filter {
    //private String policy = "default-src 'self' 'unsafe-inline' 'unsafe-eval'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self' 'unsafe-inline'; img-src 'self' data: blob: 'unsafe-inline'; frame-src 'self'; style-src 'self' 'unsafe-inline';";
    private String policy = "default-src * data: blob: imp: 'unsafe-inline' 'unsafe-eval';";
    public WebSecurityFilter(WebSecurityConfigurationProperties properties){
        super();
        if(properties!=null && !StringUtils.isEmpty(properties.getContentSecurityPolicy())){
            policy = properties.getContentSecurityPolicy();
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Content-Security-Policy", policy);
        filterChain.doFilter(request, response);
    }


    public void init(FilterConfig filterConfig) throws ServletException {}

    public void destroy() {}
}
